package com.example.weather.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class NetUtil {

    public static final String URL_WEATHER_WITH_FUTURE="https://apis.juhe.cn/simpleWeather/query?city=%E8%8B%8F%E5%B7%9E&key=5a2ee564e3a4710d862ef89ff575800a";
    //网络连接请求，。。。不要问，问就是不会
    public static String doGet(String urlStr){
        String result="";
        HttpURLConnection connection=null;
        InputStreamReader inputStreamReader=null;
        BufferedReader bufferedReader=null;
        try {
            URL url=new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);

            InputStream inputStream = connection.getInputStream();
            inputStreamReader=new InputStreamReader(inputStream);

            bufferedReader=new BufferedReader(inputStreamReader);

            StringBuilder stringBuilder=new StringBuilder();
            String line="";
            while ((line=bufferedReader.readLine())!=null){
                stringBuilder.append(line);
            }
            result=stringBuilder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (connection!=null){
                connection.disconnect();
            }

            if (inputStreamReader!=null){
                try {
                    inputStreamReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }

            if (bufferedReader!=null){
                try {
                    bufferedReader.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String getWeatherOfCity(String city){
        //获取天气URL
        String weatherUrl=URL_WEATHER_WITH_FUTURE+"&city="+city;
        Log.d("fan","----weatherUrl----"+weatherUrl);
        String weatherResult=doGet(weatherUrl);
        Log.d("fan","----weatherResult----"+weatherResult);
        return weatherResult;
    }
}
